#!/usr/bin/env python

__author__ = "Abhinav Sarkar"
__version__ = "0.1"
__license__ = "GNU Lesser General Public License"

class Country (object):
	"""A class representing a country.

	The Country class exposes the following instance properties:

		country.name
		country.topArtists
		country.topArtist
		country.topTracks
		country.topTrack
		
	The Country class exposes the following instance methods:
		
		country.AsDict()
		country.GetTopArtists()
		country.GetTopTracks()
	"""
	def __init__(self, name):
		"""An object to hold a country.

		This class is normally instantiated by the Webservice class.

		Args:
			name: the name of this country

		Usage:
			>>> import audioscrobblerws
			>>> ws = audioscrobblerws.Webservice()
			>>> country = ws.GetCountry('india')
		"""
		self.name = name

	def GetTopArtists(self):
		"""Get the top artists for this country.
		
		Returns:
			An ordered list of Artist objects corresponding to this country.
			
		Usage:
			>>> country = ws.GetCountry('india')
			>>> artists = country.GetTopArtists()
			>>> [a.name for a in artists[:10]]
			['Coldplay', 'Pink Floyd', 'Metallica', 'Linkin Park', 'U2', 'The Beatles', 
			'Iron Maiden', 'Led Zeppelin', 'Red Hot Chili Peppers', 'Radiohead']
		"""
		if not self.name:
			raise AudioscrobblerError("country name has to be set before calling this method")
		url = "http://ws.audioscrobbler.com/1.0/place/%s/topartists.xml" % self.name
		try:
			xml = Webservice()._FetchUrl(url)
		except urllib2.HTTPError,e:
			if e.code == 404:
				raise AudioscrobblerError("Country does not exist")
		data = Xml2Dict(ElementTree.XML(xml))

		artists = []
		if not 'artist' in data:
			return artists

		for artistData in data['artist']:
			artist = Artist(
				name = artistData['@name'],
				url = artistData['url'],
				thumbnail = artistData['thumbnail'],
				image = artistData['image'],
				streamable = artistData['@streamable'] == "yes"
			)
			if 'mbid' in artistData:
				artist.mbid = artistData['mbid']
			artist.count = int(artistData['@count'])
			artists.append(artist)
		return artists

	topArtists = property(GetTopArtists,
		doc = "Top artists for this country")
	topArtist = property(lambda (self): len(self.GetTopArtists()) and self.GetTopArtists()[0] or None,
		doc = "Topmost artist for this country")

	def GetTopTracks(self):
		"""Get top tracks for this country.
		
		Returns:
			An ordered list of Track objects for this country.
			
		Usage:
			>>> country = ws.GetCountry('india')
			>>> tracks = country.GetTopTracks()
			>>> [t.name for t in tracks[:5]]
			['Stairway to Heaven', 'Boulevard of Broken Dreams', 'Comfortably Numb', 'The Scientist', 
			'Nothing Else Matters']		
		"""
		if not self.name:
			raise AudioscrobblerError("country name has to be set before calling this method")
		url = "http://ws.audioscrobbler.com/1.0/place/%s/toptracks.xml" % self.name
		try:
			xml = Webservice()._FetchUrl(url)
		except urllib2.HTTPError,e:
			if e.code == 404:
				raise AudioscrobblerError("Country does not exist")
		data = Xml2Dict(ElementTree.XML(xml))

		tracks = []
		if not 'track' in data:
			return tracks

		for trackData in data['track']:
			track = Track(
				artist = Artist(
					name = trackData['artist']['@name'],
					url = trackData['artist']['url']
				),
				name = trackData['@name'],
				url = trackData['url']
			)

			if 'mbid' in trackData['artist']:
				track.artist.mbid = trackData['artist']['mbid']

			track.count = int(trackData['@count'])
			track.image = trackData['image']
			track.thumbnail = trackData['thumbnail']
			tracks.append(track)
		return tracks

	topTracks = property(GetTopTracks,
	       doc = "Top tracks for this country")
	topTrack = property(lambda (self): len(self.GetTopTracks()) and self.GetTopTracks()[0] or None,
	       doc = "Topmost track for this country")

	def AsDict(self):
		"""Returns self as a dict"""
		return self.__dict__

	def __eq__(self, other):
		return self.name == other.name

	def __ne__(self, other):
		return not self.__eq__(other)

import cElementTree as ElementTree

from artist import Artist
from webservice import Webservice
from track import Track
from xml2dict import Xml2Dict
from error import AudioscrobblerError
